const Config = require('./Config');
const fs = require('fs');
const BrowserManager = require("./BrowserManager");

class UserCookie
{
    #cookie = '';

    constructor()
    {
        this.#setCookieFromFile();
    }

    /**
     *
     * @return {string}
     */
    getCookie()
    {
        return this.#cookie
    }

    /**
     *
     * @return {boolean}
     */
    setCookie(cookie)
    {
        if ( this.#setCookieToFile(cookie) )
        {
            this.cookie = cookie;
            return true;
        }
        return false;
    }


    #getCookieFromFile()
    {
        // 初始化时尝试读取 cookie.txt
        if (fs.existsSync(Config.cookieFile))
        {
            try {
                const cookie = fs.readFileSync(Config.cookieFile, 'utf-8').trim();
                console.log('已读取 cookie.txt');
                return cookie;
            } catch (e) {
                console.error('读取 cookie.txt 出错:', e);
                return '';
            }
        }
    }

    #setCookieFromFile()
    {
        const cookie = this.#getCookieFromFile();
        if (cookie)
        {
            this.#cookie = cookie
        }

    }

    #setCookieToFile(cookie)
    {
        if (cookie.length <=0 ) {
            console.log('cookie 为空');
            return false;
        }
        // 保存到 cookie.txt
        try {
            if (!fs.existsSync(Config.dataDIr))
            {
                fs.mkdirSync(Config.dataDIr, { recursive: true });
            }
            fs.writeFileSync(Config.cookieFile, cookie, 'utf-8');
            console.log('cookie 已保存到 cookie.txt');
            return true;
        } catch (e) {
            console.error('写入 cookie.txt 出错:', e);
            return false;
        }

    }

    async getCookieFromQrcodeLogin()
    {
        const url = 'https://music.163.com';
        const browserManager = new BrowserManager();
        await browserManager.launchBrowser(false); // headful 浏览器
        let page = await browserManager.openPage(url);

        let musicU = '';

        for (let i = 0; i < 300; i++) { // 最多等待 5 分钟
            const cookies = await page.cookies();
            // 过滤掉空值，取第一个有效 MUSIC_U
            const candidate = cookies.find(c => c.name === Config.cookieName && c.value && c.value.length > 0);
            if (candidate) {
                musicU = candidate.value;
                break;
            }
            await new Promise(r => setTimeout(r, 1000)); // 每秒检查一次
        }

        if (!musicU) {
            console.warn('⚠️ 超时未获取到有效 MUSIC_U');
        } else {
            console.log('🎯 有效 MUSIC_U:', musicU);
        }

        // await browserManager.close();
        console.log("扫码登录的cookie\n"+musicU);
        await browserManager.close();
        return musicU;
    }

}



module.exports = UserCookie